<template>
  <div class="form-group">
    <label>选择年级：</label>
    <select :value="modelValue" @change="updateValue" @input="$emit('change')">
      <option 
        v-for="grade in flatGrades" 
        :key="grade.value" 
        :value="grade.value"
        :disabled="grade.disabled"
      >
        {{ grade.label }}
      </option>
    </select>
  </div>
</template>

<script>
import { computed, onMounted } from 'vue'
import { useConfig } from '../../composables/useConfig.js'

export default {
  name: 'GradeSelector',
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'change'],
  setup() {
    const { grades, loadConfig } = useConfig()

    // 将嵌套的年级数据平铺为选择器可用的格式
    const flatGrades = computed(() => {
      const result = []
      
      grades.value.forEach(grade => {
        if (grade.children) {
          // 添加分组标题（禁用选择）
          result.push({
            value: '',
            label: `── ${grade.label} ──`,
            disabled: true
          })
          // 添加子项目
          grade.children.forEach(child => {
            result.push({
              value: child.value,
              label: `　${child.label}`,
              disabled: false
            })
          })
        } else {
          // 直接添加顶级项目
          result.push({
            value: grade.value,
            label: grade.label,
            disabled: false
          })
        }
      })
      
      return result
    })

    // 组件挂载时加载配置
    onMounted(async () => {
      try {
        await loadConfig()
      } catch (error) {
        console.warn('年级选择器配置加载失败:', error)
      }
    })

    return {
      flatGrades
    }
  },
  methods: {
    updateValue(event) {
      this.$emit('update:modelValue', event.target.value)
    }
  }
}
</script>

<style scoped>
.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 0.5rem;
}

.form-group select {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
</style>